/**
 *  lbs组件封装
 */
function randomNum(n){
	var rnd="";
	for(var i=0;i<n;i++)
	rnd+=Math.floor(Math.random()*10);
	return rnd;
}

(function($){
	var $tableGrid;
	var $requestParams = {};
	var $dataSource = {read:reloadData};
	var $options;
	function LBSGrid(node,options){
		$options = $.extend(true,{
			rowNum:true,
			dataSource:{url:""},
			columns:[],
		},options);
		this.init(node,$options);
	}
	LBSGrid.prototype = {
		init:initcomponent,
		dataSource:$dataSource
	}
	function reloadData(options){
		if(options){
			delete $options.dataSource.param;
			$options.dataSource.param = options;
		}
		$tableGrid.ajax.reload();
	}
	function initcomponent(that,options){
		var table = document.createElement("table");
		table.setAttribute("class","table table-striped table-bordered");
		table.setAttribute("style","width:100%;");
		var thead = document.createElement("thead");
		var headTr = document.createElement("tr");
		headTr.setAttribute("class","heading");
		var fields = [];
		var columnDefineds = [];
		if(options.rowNum){
			var td = document.createElement("td");
			td.setAttribute("style","width:30px;");
			$(td).text("编号");
			headTr.appendChild(td);
			fields.push({});
			columnDefineds.push({
	            searchable: false,
	            orderable: false,
	            targets: 0,
	            data:null
	        });
		}
		var columns = options.columns;
		var $command={};
		for(var i in columns){
			var item = columns[i];
			var td = document.createElement("td");
			$(td).text(item.title);
			if(item.width){
				td.setAttribute("width",item.width);
			}
			headTr.appendChild(td);
			if(item.field){
				fields.push({data:item.field});
			}else{
				fields.push({});
			}
			if(item.command){
				$command = item.command;
				if(item.field&&$.isFunction(item.template)){
					columnDefineds.push({
			            targets:-1,
			            data:item.field,
			            render:function(data, type, full, meta){
			            	var _commandContent = $.map($command,function(handleItem){
								var text=handleItem.value;
								var name = handleItem.name;
								return "<a name='"+name+"' href='javascript:void(0);' style='z-index:0'>["+text+"]</a>";
							});
			            	item.template(data,_commandContent);
			            	_commandContent = $.map(_commandContent,function(item){
					    		if(item!=null){return item;}
					    	});
			            	return _commandContent.join("</span>&nbsp;<span>");
			            }
			        });
				}else{
					commandContent = $.map($command,function(handleItem){
						var text=handleItem.value;
						var name = handleItem.name;
						return "<a name='"+name+"' href='javascript:void(0);' style='z-index:0'>["+text+"]</a>";
					});
					columnDefineds.push({
			            targets:-1,
			            data:null,
			            defaultContent:commandContent.join("</span>&nbsp;<span>")
			        });
				}
			}else if($.isFunction(item.template)){
				var index = Number(i)+1;
				var handle = item.template;
				columnDefineds.push({
		            targets:index,
		            data:item.field,
		            render:function(data, type, full, meta){
		            	return handle(data);
		            }
		        });
			}
		}
		thead.appendChild(headTr)
		table.appendChild(thead)
		$(that)[0].appendChild(table);
		console.log(columnDefineds);
		debugger;
		$tableGrid = $(table).DataTable({
			ordering: false,
			processing: true,
	        serverSide: true,
			ajax: function (data, callback, settings) {
				var param = {};
                param.pageSize = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
//                param.start = data.start;//开始的记录序号
                param.pageNo = (data.start / data.length)+1;//当前页码
                param = $.extend(param,$options.dataSource.param);
                $options.dataSource.data = param;
				$.ajax($.extend({
				    type: "post",
				    dataType:"JSON",
				},$options.dataSource))
				.done(function(response){
					var returnData = {};
					 returnData.draw = data.draw;
                     returnData.recordsTotal = response.total|0;
                     returnData.recordsFiltered = response.total|0;
                     if(Object.keys(response.result).length>0){
                    	 returnData.data = response.result;
                     }else{
                    	 returnData.data = [];
                     }
                     callback(returnData);
				})
				.fail(function(response){
					
				});
			},
			columns: fields,
			renderer: "bootstrap",
			pagingType: "simple_numbers",
	        fnCreatedRow: function (row, data, index) {
	        	if(options.rowNum){
	        		$('td', row).eq(0).html(index + 1);
	        	}
	        },
	        columnDefs:columnDefineds,
			bFilter: false,
			dom: "t<'row'<'col-sm-5'i><'col-sm-7'p>>",
			language: {
	            lengthMenu: "每页显示 _MENU_ 条记录",
	            zeroRecords: "抱歉，没有找到",
	            info: "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
	            infoEmpty: "没有数据",
	            infoFiltered: "(从 _MAX_条数据中检索)",
	            paginate:{
	            	first:"首页",
	            	last:"尾页",
	            	next:"下一页",
	            	previous:"上一页"
	            }
	        }
		});
		
		$tableGrid.on( 'search.dt', function () {
			$tableGrid.column(0).nodes().each( function (cell, i) {
	            cell.innerHTML = i+1;
	        } );
	    } ).draw();
		
		if(Object.keys($command).length>0){
			$.map($command,function(handleItem){
				console.log("a[name='"+handleItem.name+"']");
				if(handleItem.click){
					$(table).on('click', "a[name='"+handleItem.name+"']", function (e) {
						var tr = $(e.target).closest("tr");
						var data = $tableGrid.row(tr).data();
						handleItem.click(data);
						e.preventDefault();
					});
				}
			});
		}
	}
	$.fn.LBSGrid = function(options){
		var that = this;
		var plugin;
		this.each(function(){
			plugin = $(this).data("LBSGrid");
			if(!plugin){
				if(!options){options={}}
				plugin = new LBSGrid($(this),options);
				$(this).data("LBSGrid",plugin);
			}
		});
		return plugin;
	}
})(jQuery);

/**-------------------------------------------------image upload start---------------------------------------------------**/
/**依赖JS：/plugins/fileinput/fileinput.js                                                                               **/
/**依赖CSS：/plugins/fileinput/fileinput.min.css                                                                         **/
(function($){
	var $options={};
	var $fileInput;
	var d = $.Deferred();
	function LBSImageUpload(node,options){
		var $elements = node;
		console.log($elements);
		$options = $.extend(true,{
			success:function success(){},
			error:function error(){},
			autoUpload:true//自动上传
		},{
			language: 'zh', //设置语言
		    uploadUrl: "", //上传的地址
		    allowedFileExtensions: ['jpg','png','bmp'],//接收的文件后缀
		    uploadAsync: true, //默认异步上传
		    showUpload: false, //是否显示上传按钮
		    showRemove : false, //显示移除按钮
		    showPreview : false, //是否显示预览
		    showCancel: false,
		    showCaption: false,//是否显示标题
		    browseClass: "btn lbs-btn upload-btn-width", //按钮样式     
		    dropZoneEnabled: false,//是否显示拖拽区域
		    maxFileSize: 10240,//单位为kb，如果为0表示不限制文件大小
		    maxFileCount: 1, //表示允许同时上传的最大文件个数
		    enctype: 'multipart/form-data',
		    validateInitialCount:true,
		    ajaxSettings:{
		    	success:successHandle
		    }
		},options);
		this.init(node,$options);
		
		function successHandle(e){
			$($elements).data("fileinput").reset();
			$($elements).data("fileinput").enable();
			e.currentTarget = $elements
			$options.success(e);
		}
	}
	LBSImageUpload.prototype = {
		init:initcomponent
	}
	function initcomponent(that,options){
		var text =that[0].defaultValue;
		$.fn.fileinputLocales.zh.browseLabel=text+'&hellip;';
		$.fn.fileinputLocales.zh.browseIcon="";
		$fileInput = that.fileinput(options);
		if(options.autoUpload){
			that.on("filebatchselected", function(event, files) {
		        $(this).fileinput("upload");
		        event.preventDefault();
		    });
		}
	}
	$.fn.LBSImageUpload = function(options){
		var that = this;
		var plugin;
		this.each(function(){
			plugin = $(this).data("LBSImageUpload");
			if(!plugin){
				if(!options){options={}}
				plugin = new LBSImageUpload($(this),options);
				$(this).data("LBSImageUpload",plugin);
			}
		});
		return plugin;
	}
})(jQuery);
/**-------------------------------------------------image upload end----------------------------------------------------**/
(function($){
	function LBSInputPlusMinus(node,options){
		var $options = $.extend({},options);
		this.init(node,$options);
	}
	LBSInputPlusMinus.prototype = {
		init:initcomponent
	}
	function initcomponent(that,options){
		$("div").append(that[0]);
//		<div class="input-group">
//	        <span class="input-group-btn">
//	            <button type="button" class="btn btn-default btn-number" disabled="disabled" data-type="minus" data-field="quant[1]">
//	                <span class="glyphicon glyphicon-minus"></span>
//	            </button>
//	        </span>
//	        <input type="text" name="quant[1]" class="form-control input-number" value="1" min="1" max="10">
//	        <span class="input-group-btn">
//	            <button type="button" class="btn btn-default btn-number" data-type="plus" data-field="quant[1]">
//	                <span class="glyphicon glyphicon-plus"></span>
//	            </button>
//	        </span>
//	    </div>
	}
	$.fn.LBSInputPlusMinus = function(options){
		var that = this;
		var plugin;
		this.each(function(){
			plugin = $(this).data("LBSInputPlusMinus");
			if(!plugin){
				if(!options){options={}}
				plugin = new LBSInputPlusMinus($(this),options);
				$(this).data("LBSInputPlusMinus",plugin);
			}
		});
		return plugin;
	}
})(jQuery);
